<template>
    <v-dialog v-model="dialogFormVisible" max-width="800px" persistent scrollable>
        <v-card>
            <v-card-title class="d-flex align-center justify-space-between pa-4">
                <div class="d-flex align-center gap-2">
                    <v-icon color="primary" size="24">mdi-cog</v-icon>
                    <span class="text-h6">审批节点配置</span>
                </div>
                <v-btn icon="mdi-close" variant="text" @click="dialogFormVisible = false" />
            </v-card-title>

                <!-- 工具栏 -->
                <div class="d-flex align-center justify-space-between pa-4">
                    <div class="d-flex align-center gap-2">
                        <v-btn 
                            color="primary" 
                                        prepend-icon="mdi-plus"
                                        @click="handleAdd" 
                                        v-if="$perms('approval_node_insert')"
                                        variant="flat"
                                    >
                                        新增节点
                                    </v-btn>
                                    <v-btn 
                                        color="success" 
                                        prepend-icon="mdi-refresh" 
                                        @click="fetchData"
                                        variant="outlined"
                                    >
                                        刷新
                                    </v-btn>
                                </div>
                                
                                <div class="d-flex align-center gap-2">
                                    <v-text-field
                                        v-model="searchKeyword"
                                        label="搜索节点名称"
                                        variant="outlined"
                                        density="compact"
                                        hide-details
                                        prepend-inner-icon="mdi-magnify"
                                        style="width: 200px;"
                                        @keyup.enter="handleSearch"
                                    />
                                    <v-btn 
                                        color="primary" 
                                        @click="handleSearch"
                                        variant="flat"
                                    >
                                        搜索
                                    </v-btn>
                                </div>
                            </div>

            
            <v-card-text class="pa-4">
                <v-container fluid class="pa-0">
                
                    <!-- 加载状态 -->
                    <v-progress-linear
                        v-if="loading"
                        indeterminate
                        color="primary"
                        class="mb-4"
                    />

                    <!-- 节点列表 -->
                    <div v-if="!loading && dataList.length > 0" class="d-flex flex-column gap-3">
                        <v-card 
                            v-for="(item, index) in filteredDataList" 
                            :key="item.id"
                            class="elevation-10 ma-2"
                        >
                            <v-card-text class="pa-4">
                                <div class="d-flex align-center justify-space-between">
                                    <div class="d-flex align-center gap-3">
                                        <!-- 节点序号 -->
                                        <v-avatar 
                                            :color="getNodeColor(item.type)" 
                                            size="40"
                                            class="font-weight-bold"
                                        >
                                            {{ item.sort }}
                                        </v-avatar>
                                        
                                        <!-- 节点信息 -->
                                        <div>
                                            <div class="d-flex align-center gap-2 mb-1">
                                                <span class="text-h6 font-weight-medium">{{ item.title }}</span>
                                                <v-chip 
                                                    :color="getTypeColor(item.type)" 
                                                    size="small" 
                                                    variant="flat"
                                                >
                                                    {{ getTypeLabel(item.type) }}
                                                </v-chip>
                                                <v-chip 
                                                    :color="getAndOrColor(item.andOr)" 
                                                    size="small" 
                                                    variant="flat"
                                                >
                                                    {{ getAndOrLabel(item.andOr) }}
                                                </v-chip>
                                            </div>
                                            
                                            <div class="d-flex align-center gap-4 text-body-2 text-medium-emphasis">
                                                <div class="d-flex align-center gap-1">
                                                    <v-icon size="16" color="info">mdi-account-group</v-icon>
                                                    <span>{{ getRoleTypeLabel(item.roleType) }}</span>
                                                </div>
                                                <div class="d-flex align-center gap-1" v-if="item.ids">
                                                    <v-icon size="16" color="warning">mdi-identifier</v-icon>
                                                    <span>{{ item.ids }}</span>
                                                </div>
                                                <div class="d-flex align-center gap-1" v-if="item.remark">
                                                    <v-icon size="16" color="success">mdi-note-text</v-icon>
                                                    <span>{{ item.remark }}</span>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- 操作按钮 -->
                                    <div class="d-flex gap-1">
                                        <v-btn 
                                            size="small" 
                                            color="primary" 
                                            variant="text" 
                                            icon="mdi-pencil"
                                            @click="handleEdit(item)"
                                            v-if="$perms('approval_node_update')"
                                        />
                                        <v-btn 
                                            size="small" 
                                            color="error" 
                                            variant="text" 
                                            icon="mdi-delete"
                                            @click="handleDelete(item)"
                                            v-if="$perms('approval_node_delete')"
                                        />
                                    </div>
                                </div>
                            </v-card-text>
                        </v-card>
                    </div>

                    <!-- 空状态 -->
                    <v-card v-else-if="!loading && dataList.length === 0" class="elevation-10">
                        <v-card-text class="text-center py-8">
                            <v-icon size="64" color="grey-lighten-1" class="mb-4">mdi-cog-off</v-icon>
                            <div class="text-h6 text-grey-darken-1 mb-2">暂无审批节点</div>
                            <div class="text-body-2 text-grey">点击"新增节点"按钮开始配置审批流程</div>
                        </v-card-text>
                    </v-card>

                    <!-- 分页 -->
                    <v-card v-if="total > (queryParams.pageSize || 10)" class="elevation-10 mt-4">
                        <v-card-text class="pa-4">
                            <v-pagination
                                v-model="queryParams.pageNo"
                                :length="Math.ceil(total / (queryParams.pageSize || 10))"
                                :total-visible="7"
                                @update:model-value="handlePageChange"
                            />
                        </v-card-text>
                    </v-card>
                </v-container>
            </v-card-text>

            <!-- 编辑对话框 -->
            <ApprovalNodeManagementEdit ref="editRef" type="sign" @fetch-data="fetchData" />

        
        </v-card>
    </v-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import {
    getList,
    doDelete,
    doDeleteAll,
    doExportExcel,
    doDownloadTemplate,
    doImportExcel,
    type ApprovalNodeModel,
    type ApprovalNodeQueryParams,
    type ApiResponse,
    type PageResult
} from '@/api/approval/node/ApprovalNodeManagementApi';
import ApprovalNodeManagementEdit from '@/views/modules/approval/node/components/ApprovalNodeManagementEdit.vue';
import { getDictListSync } from '@/utils/dict';
import { useMessage } from '@/composables/useMessage';

const { success: showSuccess, error: showError } = useMessage();
const dialogFormVisible = ref(false);
const loading = ref(false);
const dataList = ref<ApprovalNodeModel[]>([]);
const total = ref(0);
const selectRows = ref<string[]>([]);
const editRef = ref();
const importDialog = ref(false);
const uploadFile = ref<File[]>([]);
const showMoreQuery = ref(false);
const searchKeyword = ref('');

// 查询参数
const queryParams = reactive<ApprovalNodeQueryParams>({
    pageNo: 1,
    pageSize: 10,
    type_EQ: 'sign',
    sort_ORDER: 'ASC'
});

// 字典数据
const dict = reactive({});

// 过滤后的数据列表
const filteredDataList = computed(() => {
    if (!searchKeyword.value) {
        return dataList.value;
    }
    return dataList.value.filter(item => 
        item.title?.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
        item.remark?.toLowerCase().includes(searchKeyword.value.toLowerCase())
    );
});

// 显示配置
function showConfig() {
    dialogFormVisible.value = true;
    fetchData();
}

// 暴露方法给父组件
defineExpose({
    showConfig
});

// 搜索处理
function handleSearch() {
    queryParams.pageNo = 1;
    fetchData();
}

// 获取节点颜色
function getNodeColor(type: string): string {
    const colors = ['primary', 'success', 'warning', 'error', 'info'];
    return colors[type.length % colors.length];
}

// 获取类型标签
function getTypeLabel(type: string): string {
   
    return type || '未知类型';
}

// 获取类型颜色
function getTypeColor(type: string): string {
    const colorMap: Record<string, string> = {
        'adn-or': 'success',
        'adn-and': 'primary',
        'adn-end': 'error'
    };
    return colorMap[type] || 'grey';
}

// 获取与或标签
function getAndOrLabel(andOr: string): string {
    const andOrMap: Record<string, string> = {
        'and': '与',
        'or': '或'
    };
    return andOrMap[andOr] || andOr;
}

// 获取与或颜色
function getAndOrColor(andOr: string): string {
    const colorMap: Record<string, string> = {
        'and': 'warning',
        'or': 'info'
    };
    return colorMap[andOr] || 'grey';
}

// 获取角色类型标签
function getRoleTypeLabel(roleType: number): string {
    const roleTypeMap: Record<number, string> = {
        1: '个人',
        2: '角色'
    };
    return roleTypeMap[roleType] || '未知';
}

// 获取数据
async function fetchData() {
    loading.value = true;
    try {
        const { data }: ApiResponse<PageResult<ApprovalNodeModel>> = await getList(queryParams);
        if (data) {
            dataList.value = data.rows || [];
            total.value = data.total || 0;
        }
    } catch (error) {
        console.error('Failed to fetch data:', error);
        showError('获取数据失败');
    } finally {
        loading.value = false;
    }
}

// 重置查询
function resetQuery() {
    Object.assign(queryParams, {
        pageNo: 1,
        pageSize: 10,
    });
    fetchData();
}

// 分页处理
function handlePageChange(page: number) {
    queryParams.pageNo = page;
    fetchData();
}

function handlePageSizeChange(size: number) {
    queryParams.pageSize = size;
    queryParams.pageNo = 1;
    fetchData();
}

// 选择处理
function setSelectRows(selected: string[]) {
    selectRows.value = selected;
}

// 新增
function handleAdd() {
    editRef.value?.showEdit();
}

// 编辑
function handleEdit(row: ApprovalNodeModel) {
    editRef.value?.showEdit(row);
}

// 删除
async function handleDelete(row: ApprovalNodeModel) {
    if (!confirm(`确定要删除节点"${row.title}"吗？`)) return;

    try {
        const { msg } = await doDelete({ id: row.id! });
        showSuccess(msg || '删除成功');
        fetchData();
    } catch (error) {
        console.error('Delete failed:', error);
        showError('删除失败');
    }
}

// 批量删除
async function handleDeleteBatch() {
    if (!selectRows.value.length) {
        showError('请选择要删除的数据');
        return;
    }

    if (!confirm(`确定要删除选中的 ${selectRows.value.length} 条记录吗？`)) return;

    try {
        const { msg } = await doDeleteAll({ ids: selectRows.value.join(',') });
        showSuccess(msg || '批量删除成功');
        selectRows.value = [];
        fetchData();
    } catch (error) {
        console.error('Batch delete failed:', error);
        showError('批量删除失败');
    }
}

// 导出Excel
async function handleExport() {
    try {
        await doExportExcel(queryParams);
        showSuccess('导出成功');
    } catch (error) {
        console.error('Export failed:', error);
        showError('导出失败');
    }
}

// 下载模板
async function handleDownloadTemplate() {
    try {
        await doDownloadTemplate();
        showSuccess('下载成功');
    } catch (error) {
        console.error('Download template failed:', error);
        showError('下载模板失败');
    }
}

// 导入Excel
function handleImport() {
    importDialog.value = true;
    uploadFile.value = [];
}

async function confirmImport() {
    if (!uploadFile.value.length) {
        showError('请选择要上传的文件');
        return;
    }

    const formData = new FormData();
    formData.append('file', uploadFile.value[0]);

    try {
        const response = await doImportExcel(formData);
        showSuccess(response.data?.msg || '导入成功');
        importDialog.value = false;
        fetchData();
    } catch (error) {
        console.error('Import failed:', error);
        showError('导入失败');
    }
}

// 初始化字典数据
function initDict() {
    // 可以在这里初始化字典数据
}

// 生命周期
onMounted(() => {
    initDict();
});
</script>

<style lang="scss" scoped>
.gap-2 {
    gap: 8px;
}

.gap-1 {
    gap: 4px;
}

.gap-3 {
    gap: 12px;
}

.gap-4 {
    gap: 16px;
}

.border-primary {
    border: 2px solid rgb(var(--v-theme-primary));
}

.v-card {
    transition: all 0.3s ease;
    
    &:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15) !important;
    }
}
</style>